package com.qf.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.ServletRequest;
import java.io.Serializable;

public class AppSessionManager extends DefaultWebSessionManager {

    private final String SESSION_KEY = "shiro-session-key";

    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);
        if (sessionId == null) {
            return null;
        }

        WebSessionKey webSessionKey = null;
        // 强转.
        if(sessionKey instanceof WebSessionKey) webSessionKey = (WebSessionKey) sessionKey;

        // 通过WebSessionKey 获取request对象
        ServletRequest req = webSessionKey.getServletRequest();

        // 先去request域中
        Session session = (Session) req.getAttribute(SESSION_KEY);
        // 如果有,直接返回
        if(session != null){
            return session;
        }else{
            // 如果没有,去redis查询,并将结果放到request域中一份
            session = retrieveSessionFromDataSource(sessionId);
            // 如果查询到是null
            if (session == null) {
                String msg = "Could not find session with ID [" + sessionId + "]";
                throw new UnknownSessionException(msg);
            }
            // 将不为null的session放到req域中.
            req.setAttribute(SESSION_KEY,session);
            // 返回
            return session;
        }
    }
}
